import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

/**
 *
 * @author Bora SAYINER
 * @since Dec 28, 2014 1:25:44 PM
 * @version 1.0
 */
public class MainFrame {

	private JFrame frmMain;
	private List<Horse> horses;

	public MainFrame() {
		this.horses = new ArrayList<Horse>();
		for (int i = 0; i < 4; i++) {
			horses.add(new Horse(String.format("%d. at", i + 1)));
		}
		initializeComponents();
	}

	private void initializeComponents() {
		frmMain = new JFrame();
		frmMain.setTitle("At yarışı");
		frmMain.setSize(800, 600);
		frmMain.setLocationRelativeTo(null);
		frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		{
			{
				JPanel pnlCenter = new JPanel();
				BoxLayout boxLayout = new BoxLayout(pnlCenter, BoxLayout.Y_AXIS);
				pnlCenter.setLayout(boxLayout);
				{
					for (Horse horse : horses) {
						pnlCenter.add(horse);
					}
				}
				frmMain.add(pnlCenter, BorderLayout.CENTER);
			}
			{
				JPanel pnlSouth = new JPanel();
				{
					JButton btnStart = new JButton("Yarışa Başla");
					btnStart.addActionListener(new ActionListener() {

						Timer timer = null;

						@Override
						public void actionPerformed(ActionEvent e) {
							for (Horse horse : horses) {
								Point location = horse.getLocation();
								horse.setLocation(0, location.y);
							}
							String atAdi = JOptionPane.showInputDialog(null, "Hangi at kazanacak");
							TimerTask timerTask = new TimerTask() {

								@Override
								public void run() {
									Dimension formSize = frmMain.getSize();
									Horse sampiyon = null;
									for (Horse horse : horses) {
										Point atLocation = horse.getLocation();
										Dimension atSize = horse.getSize();
										if (atLocation.x + atSize.width >= formSize.width) {
											sampiyon = horse;
											break;
										}
									}
									if (sampiyon == null) {
										for (Horse horse : horses) {
											horse.run();
										}
										frmMain.repaint();
									} else {
										timer.cancel();
										if (String.format("%s. at", atAdi).equals(sampiyon.getNickName())) {
											JOptionPane.showMessageDialog(null, "Kazandınız");
										} else {
											JOptionPane.showMessageDialog(null, "Kaybettiniz");
										}
									}
								}
							};
							timer = new Timer();
							timer.schedule(timerTask, 0, 100);
						}
					});
					pnlSouth.add(btnStart);
				}
				frmMain.add(pnlSouth, BorderLayout.SOUTH);
			}
		}
	}

	public void setVisible(boolean visible) {
		frmMain.setVisible(visible);
	}
}
